/* utils*/
import { storageGet, storageSet } from "@src/util/storage.ts";
import _ from 'lodash'
/* enum*/
import { SelectModule } from "@src/mixins/selectColumnMixin/SelectColumnKeyEnum";
import { FieldTypeMappingEnum } from "@model/enum/FieldMappingEnum";

// 列表筛选字段类型
const LIST_FILTER_FORM_TYPE = ['info', 'separator', 'attachment', 'autograph', FieldTypeMappingEnum.JsCodeBlock];
export default {
    name: 'select-column-mixin',
    data() {
        return {
            columns: [],
            listKey: '',
            selectModule: '',
            serverCache: false,
        }
    },
    methods: {
        /*打开选择列*/
        openSelectColumn() {
            this.$refs.advanced?.open(this.columns, {});
        },

        /*保存选择列配置*/
        saveColumnStatus(event) {
            try {
                let columns = _.cloneDeep(event.data || [])

                this.columns = []
                this.$nextTick(async () => {

                    this.$set(this, 'columns', columns.slice());
                    await this.saveColumnStatusToStorage()
                    this.$message.success(this.$t('common.base.saveSuccess'));
                })
            } catch (e) {
                console.error(e)
            }
        },

        /*获取列表的一些key,listKeyOther如果有值，用listKeyOther（一般用于有状态，有类型的列表）*/
        getSelectKey(mode, serverCache = false, listKeyOther = '') {
            const { module = '', listKey = ''} = SelectModule?.[mode] ?? {}

            this.selectModule = module;
            this.listKey = listKeyOther ? listKeyOther : listKey
            this.serverCache = serverCache;
        },
        
        /*保存选择列配置*/
        async saveColumnStatusToStorage() {
            try {
                const localStorageData = await this.getLocalStorageData()
                let columnsStatus = null


                const columnsList = this.columns.map(c => ({
                    field: c.field,
                    show: c.show,
                    width: c.width,
                }));

                if (localStorageData.columnStatus) {
                    localStorageData.columnStatus = columnsList;
                    columnsStatus = localStorageData.columnStatus;
                } else {
                    columnsStatus = columnsList;
                }
                
                await this.saveDataToStorage('columnStatus', columnsStatus);
            } catch (e) {
                console.error(e)
            }
        },

        /*保存数据*/
        async saveDataToStorage(key, value) {
           try {
               const data = await this.getLocalStorageData()
               data[key] = value
               await storageSet(this.listKey, JSON.stringify(data), this.selectModule, this.serverCache)
           } catch (e) {
               console.error(e)
           }
        },

        /*获取选择列配置*/
        async getLocalStorageData() {
            let data = {}
            try {
                data = await storageGet(this.listKey, {}, this.selectModule, this.serverCache)
                data = JSON.parse(data)
            } catch (error) {
                data = {}
                console.error('Caused ~ getLocalStorageData ~ error', error)
            }

            return data
        },

        /*获取选择列表单*/
        async getLocalColumns() {
            let columnStatus = []
            try {
                const localStorageData = await this.getLocalStorageData();
                columnStatus = localStorageData?.columnStatus ?? [];

                columnStatus= columnStatus
                    .map((i) => (typeof i == 'string' ? { field: i, show: true } : i))
                    .reduce((acc, col, currentIndex) => {
                        acc[col.field] = {
                            field: col,
                            index: currentIndex,
                        }
                        return acc
                    }, {});
            } catch (e) {
                console.error(e)
            }

            return columnStatus;
        },

        /*选择列排序*/
        buildSortFields(originFields = [], fieldsMap = {}) {
            let fields = [];
            let unsortedFields = []

            // 排序
            originFields.forEach(originField => {
                let { fieldName  = ''} = originField

                let field = fieldsMap[fieldName]

                if (field) {
                    let { index } = field
                    fields[index] = originField
                } else {
                    unsortedFields.push(originField)
                }
            })
            fields = fields.concat(unsortedFields)

            // 选择列配置 是否勾选（显示）&宽度
            fields = fields.map((col) => {
                let show = col.show;
                let width = col.width;
                let localField = fieldsMap[col.field]?.field || null;

                if (null != localField) {
                    if (localField.width) {
                        width = typeof localField.width == 'number'
                            ? `${localField.width}px`
                            : localField.width;
                    }
                    show = localField.show !== false;
                }

                col.show = show;
                col.width = width;
                col.minWidth = col.width || 150;
                col.type = 'column';
                return col;
            }).filter(f => !LIST_FILTER_FORM_TYPE.includes(f.formType));

            return fields
        },

        /*拖拽表头*/
        headerDragend (newWidth, oldWidth, column, event) {
            let data = this.columns
                .map((item) => {
                    if (item.fieldName === column.property) {
                        item.width = column.width;
                    }
                    return item;
                })
                .map((item) => {
                    return {
                        field: item.field,
                        show: item.show,
                        width: item.width,
                    };
                });
            this.modifyColumnStatus({ type: 'column', data });
        },

        /*修改选择列设置*/
        modifyColumnStatus (event) {
            let columns = event.data || [],
                colMap = columns.reduce(
                    (acc, col) => (acc[col.field] = col) && acc,
                    {}
                );
            this.columns.forEach((col) => {
                let newCol = colMap[col.field];
                if (null != newCol) {
                    this.$set(col, 'show', newCol.show);
                    this.$set(col, 'width', newCol.width);
                }
            });

            this.saveColumnStatusToStorage();
        },
    },
}